package com.sywb.chuangyebao;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Point;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkRequest;
import android.os.Build;
import android.support.multidex.MultiDex;
import android.text.TextUtils;
import android.view.WindowManager;

import com.alibaba.sdk.android.push.CloudPushService;
import com.alibaba.sdk.android.push.CommonCallback;
import com.alibaba.sdk.android.push.noonesdk.PushServiceFactory;
import com.alibaba.sdk.android.push.notification.BasicCustomPushNotification;
import com.alibaba.sdk.android.push.notification.CustomNotificationBuilder;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationListener;
import com.mob.MobSDK;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.view.LoginActivity;
import com.tencent.rtmp.TXLiveBase;
import com.tencent.rtmp.TXLiveConstants;
import com.tencent.ugc.TXUGCBase;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;

import org.bining.footstone.App;
import org.bining.footstone.BaseApplication;
import org.bining.footstone.db.DataBaseConfig;
import org.bining.footstone.db.DbManager;
import org.bining.footstone.db.assit.SQLiteHelper;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;
import org.bining.footstone.rxjava.rxbus.annotation.Subscribe;
import org.bining.footstone.rxjava.rxbus.annotation.Tag;
import org.bining.footstone.rxjava.rxbus.thread.ThreadMode;
import org.bining.footstone.utils.ApkUtils;
import org.bining.footstone.utils.NetUtils;
import org.bining.footstone.utils.SharedUtils;

import butterknife.ButterKnife;

/**
 * Application ea2fa75569224d8085b4d5196300d11a
 */
public class MyApplication extends BaseApplication {

    public static final float DESIGN_WIDTH = 750; //绘制页面时参照的设计图宽度

    private BroadcastReceiver broadcastReceiver;

    //声明AMapLocationClient类对象
    private AMapLocationClient mLocationClient = null;

    @Override
    public void onCreate() {
        super.onCreate();

        MobclickAgent.openActivityDurationTrack(false);

        MobSDK.init(this);

        initCloudChannel(this);

        if (ApkUtils.isNamedProcess(this, getPackageName())) {
            if (App.isDebug()) {
                // LogSettings settings = new LogSettings.Builder().showMethodLink(true).showThreadInfo(true).methodOffset(1).logPriority(BuildConfig.DEBUG ? Log.VERBOSE : Log.ASSERT).build();
                // Logger.plant(new PrettyTree(settings));
                Logger.plant(new Logger.DebugTree());
            }
            Logger.i("启动主进程");
            Logger.e("PushServiceFactory.getCloudPushService().getDeviceId():" + PushServiceFactory.getCloudPushService().getDeviceId());

            TXUGCBase.getInstance().setLicence(this, "http://license.vod2.myqcloud.com/license/v1/d1f6584efc7a9c98795a636a57aa10c2/TXUgcSDK.licence", "9b74faec9fceb26e9c93e5cfbe85e0ef");
            TXLiveBase.setConsoleEnabled(true);
            TXLiveBase.setLogLevel(TXLiveConstants.LOG_LEVEL_VERBOSE);

            UMConfigure.init(this, UMConfigure.DEVICE_TYPE_PHONE, null);
            UMConfigure.setLogEnabled(true);

            RxBus.get().register(getApplicationContext());

            initDB(2);

            ButterKnife.setDebug(App.isDebug());
        } else {
            Logger.i("启动其他进程");
        }
    }

    @Override
    public void onTerminate() {
        RxBus.get().unregister(getApplicationContext());
        super.onTerminate();
    }

    /**
     * 启动网络广播
     */
    @Subscribe(thread = ThreadMode.IO, tags = {@Tag(Manifest.permission.WRITE_SETTINGS)})
    public void netwotk(String data) {
        Logger.e("启动网络广播");
        receiveNetwork();
    }

    /**
     * 收到需要登录广播
     */
    @Subscribe(thread = ThreadMode.MAIN_THREAD, tags = {@Tag(Constants.HTTP_SSO_LOGIN)})
    public void needLogin(String data) {
        Logger.e("收到需要登录广播：" + data);
        SharedUtils.put(Constants.USERISLOGIN, false);
        SharedUtils.put(Constants.USERMOBILEVERIFY, false);
        RxBus.get().post(Constants.USERISLOGIN, "false");
        Activity activity = getAppComponent().appManager().getCurrentActivity();
        Logger.e("最后一个activity：" + activity);
        if (activity != null && !activity.isFinishing()) {
            activity.startActivity(new Intent(activity, LoginActivity.class));
        }
    }

    /**
     * 初始化云推送通道
     */
    private void initCloudChannel(Context applicationContext) {
        PushServiceFactory.init(applicationContext);
        SharedUtils.put(Constants.USERDEVICEID, PushServiceFactory.getCloudPushService().getDeviceId());
        CloudPushService pushService = PushServiceFactory.getCloudPushService();
        pushService.register(applicationContext, new CommonCallback() {
            @Override
            public void onSuccess(String response) {
                Logger.d("阿里云推送初始化成功:" + PushServiceFactory.getCloudPushService().getDeviceId());
                SharedUtils.put(Constants.USERDEVICEID, PushServiceFactory.getCloudPushService().getDeviceId());

                initLocation();

                String openId = SharedUtils.getString(Constants.USEROPENID);
                if (!TextUtils.isEmpty(openId)) {
                    PushServiceFactory.getCloudPushService().bindAccount(openId, new CommonCallback() {
                        @Override
                        public void onSuccess(String s) {
                            Logger.d("阿里云推送绑定账号成功");
                        }

                        @Override
                        public void onFailed(String s, String s1) {
                            Logger.d("阿里云推送绑定账号失败");
                        }
                    });
                }
                // PushServiceFactory.getCloudPushService().

                boolean isMessageNotice = SharedUtils.getBoolean(Constants.ISMESSAGENOTICE, false);
                boolean isOpenSound = SharedUtils.getBoolean(Constants.ISOPENSUOUND, false);
                boolean isOpenVibration = SharedUtils.getBoolean(Constants.ISOPENVIBRATION, false);

                BasicCustomPushNotification notification = new BasicCustomPushNotification();
                if (isMessageNotice && (isOpenSound || isOpenVibration)) {
                    if (isOpenSound && isOpenVibration) {
                        notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_VIBRATE_AND_SOUND);
                    } else if (isOpenSound) {
                        notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_SOUND);
                    } else {
                        notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_VIBRATE);
                    }
                } else {
                    notification.setRemindType(BasicCustomPushNotification.REMIND_TYPE_SILENT);
                }
                CustomNotificationBuilder.getInstance().setCustomNotification(1, notification);
            }

            @Override
            public void onFailed(String errorCode, String errorMessage) {
                Logger.d("阿里云推送初始化失败 ErrorCode:" + errorCode + " ErrorMessage:" + errorMessage);
            }
        });
    }

    private void initLocation() {
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //异步获取定位结果
        AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation amapLocation) {
                if (amapLocation != null) {
                    if (amapLocation.getErrorCode() == 0) {
                        //解析定位结果
//                        amapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
//                        amapLocation.getLatitude();//获取纬度
//                        amapLocation.getLongitude();//获取经度
//                        amapLocation.getAccuracy();//获取精度信息
//                        amapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
//                        amapLocation.getCountry();//国家信息
//                        amapLocation.getProvince();//省信息
//                        amapLocation.getCity();//城市信息
//                        amapLocation.getDistrict();//城区信息
//                        amapLocation.getStreet();//街道信息
//                        amapLocation.getStreetNum();//街道门牌号信息
//                        amapLocation.getCityCode();//城市编码
//                        amapLocation.getAdCode();//地区编码
//                        amapLocation.getAoiName();//获取当前定位点的AOI信息
//                        amapLocation.getBuildingId();//获取当前室内定位的建筑物Id
//                        amapLocation.getFloor();//获取当前室内定位的楼层
//                        amapLocation.getGpsAccuracyStatus();//获取GPS的当前状态
//                        //获取定位时间
//                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                        Date date = new Date(amapLocation.getTime());
//                        df.format(date);
                        mLocationClient.stopLocation();

                        Logger.e("Location>> 纬度:" + amapLocation.getLatitude() + " 经度:" + amapLocation.getLongitude() + " Address:" + amapLocation.getAddress());

                        HttpUtils.positionAdd(amapLocation.getAddress(), amapLocation.getLatitude(), amapLocation.getLongitude(), new HttpCallback<Object>() {
                            @Override
                            public void onSuccess(Object o) {
                                Logger.e("上传定位信息成功");
                            }
                        });
                    } else {
                        //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                        Logger.e("AmapError" + "location Error, ErrCode:"
                                + amapLocation.getErrorCode() + ", errInfo:"
                                + amapLocation.getErrorInfo());
                    }
                }
            }
        };
        //设置定位回调监听
        mLocationClient.setLocationListener(mAMapLocationListener);
        //启动定位
        mLocationClient.startLocation();
    }

    /**
     * 初始化数据库
     *
     * @param dbVersion 数据库版本
     */
    private void initDB(int dbVersion) {
        DataBaseConfig dataBaseConfig = new DataBaseConfig(this, "ChuangYeBao.db", dbVersion, new SQLiteHelper.OnUpdateListener() {
            @Override
            public void onUpdate(SQLiteDatabase sqLiteDatabase, int i, int i1) {
            }
        });
        dataBaseConfig.setOnDataChangeListener(new DataBaseConfig.OnDataChangeListener() {
            @Override
            public void onDataChange(String tableName) {
                Logger.e("onDataChange:" + tableName);
                RxBus.get().post(tableName, tableName);
            }
        });
        DbManager.init(1, dataBaseConfig);
    }

    /**
     * 接收网络变化广播
     */
    private void receiveNetwork() {
        if (broadcastReceiver != null) {
            return;
        }
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Logger.e("My intent.getAction():" + intent.getAction());
                switch (intent.getAction()) {
                    case ConnectivityManager.CONNECTIVITY_ACTION:
                        RxBus.get().post(ConnectivityManager.CONNECTIVITY_ACTION, ConnectivityManager.CONNECTIVITY_ACTION);
                        break;
                    case Intent.ACTION_TIME_TICK:
                        RxBus.get().post(Intent.ACTION_TIME_TICK);
                        break;
                    case Intent.ACTION_SCREEN_OFF:
                        break;
                    case Intent.ACTION_SCREEN_ON:
                        break;
                }
            }
        };

        IntentFilter intentFilter = new IntentFilter();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            try {
                ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                connectivityManager.requestNetwork(new NetworkRequest.Builder().build(), new ConnectivityManager.NetworkCallback() {
                    @Override
                    public void onAvailable(Network network) {
                        super.onAvailable(network);
                        RxBus.get().post(ConnectivityManager.CONNECTIVITY_ACTION, ConnectivityManager.CONNECTIVITY_ACTION);
                        Logger.e("NetworkCallback onAvailable:" + NetUtils.isConnected());
                        // BaseMQTTService.startAndConnect(getApplicationContext());
                        // managerNetworkDialog(true);
                    }

                    @Override
                    public void onLost(Network network) {
                        super.onLost(network);
                        RxBus.get().post(ConnectivityManager.CONNECTIVITY_ACTION, ConnectivityManager.CONNECTIVITY_ACTION);
                        Logger.e("NetworkCallback onLost:" + NetUtils.isConnected());
                        // managerNetworkDialog(false);
                    }
                });
            } catch (Exception e) {
                intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);// 网络改变广播
            }
        } else {
            intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);// 网络改变广播
        }
        intentFilter.addAction(Intent.ACTION_TIME_TICK);// 时间改变广播,每分钟发出一次
        intentFilter.addAction(Intent.ACTION_SCREEN_OFF);// 手机熄屏广播
        intentFilter.addAction(Intent.ACTION_SCREEN_ON);// 手机亮屏广播
        registerReceiver(broadcastReceiver, intentFilter);
    }

    /**
     * 分包解决64K限制
     */
    @Override
    protected void attachBaseContext(Context context) {
        super.attachBaseContext(context);
        // 分包机制
        try {
            MultiDex.install(this);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // resetDensity();
    }

    /**
     * 粗暴的屏幕适配方案(未使用)
     * 核心。使用冷门的pt作为长度单位。
     * 绘制。编写xml时完全对照设计稿上的尺寸来编写，只不过单位换为pt。 如果需要在代码中动态转换成px的话，使用TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PT, value, metrics)。
     * 预览。实时预览时绘制页面是很重要的一个环节。以1334×750的设计图为例，为了实现于正常绘制时一样的预览功能，创建一个长为1334磅，宽为750磅的设备作为预览，经换算约为21.5英寸((sqrt(1334^2+750^2))/72)。预览时选择这个设备即可
     */
    public void resetDensity() {
        Point size = new Point();
        ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getSize(size);
        getResources().getDisplayMetrics().xdpi = size.x / DESIGN_WIDTH * 72f;
    }

}
